import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // 跨域请求时发送cookie
  timeout: -1, // 请求超时进程  process.env.VUE_APP_BASE_API
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    if (store.getters.token) {
      // 让每个请求都携带令牌
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // console.log(getToken(), 666);
      config.headers["X-Token"] = getToken();
    }
    return config;
  },
  (error) => {
    // 处理请求错误
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  /**
   * 处理请求错误
   * Please return  response => response
   */

  /**
   * 通过自定义代码确定请求状态
   * 例子
   * 您还可以通过HTTP状态代码来判断状态。
   */
  (response) => {
    const res = response.data;
    // console.log(res, "拦截的数据");
    if (res.code === 10002) {
      Message({
        message: res.message,
        type: "error",
        duration: 2 * 1000,
      });
      store.dispatch("user/logout").then(() => {
        location.reload(true);
      });
    } else if (res.code == 10001) {
      Message({
        message: res.message,
        type: "error",
        duration: 2 * 1000,
      });
    } else {
      if (res.message) {
        Message({
          message: res.message,
          type: "success",
          duration: 2 * 1000,
        });
      }
      return res;
    }
  },
  (error) => {
    // console.log("err" + error); // for debug
    Message({
      message: "系统/接口维护,请稍后重试",
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
